1 Introduction
1.1 Getting Start
plotly is an R package for creating interactive web-based graphs via the open source JavaScript graphing library plotly.js. As of version 2.0 (November 17, 2015), graphs created with the plotly R package are rendered locally through the htmlwidgets framework.
2 Basic Charts
2.1 Scatter Plots
2.1.1 Basic Scatter Plot
library(plotly)
fig <- plot_ly(data = mtcars, x = ~hp, y= ~mpg, type = "scatter", mode = "markers")
fig2.1.2 Styled Scatter Plots
library(plotly)
fig <- plot_ly(data = mtcars, x = ~hp, y= ~mpg, type = "scatter",
mode = "markers",
marker = list(size = 10,
color = 'rgba(255, 182, 193, .9)',
line = list(color = 'rgba(152, 0, 0, .8)',
width = 2)))
fig <- fig %>% layout(title = 'Styled Scatter',
yaxis = list(zeroline = FALSE),
xaxis = list(zeroline = FALSE))
fig2.2 Line Plots
2.2.1 Basic Line Plot
library(plotly)
x <- c(1:100)
random_y <- rnorm(100, mean = 0)
data <- data.frame(x, random_y)
fig <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines')
fig2.2.2 Line Plots Mode
library(plotly)
trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)
data <- data.frame(x, trace_0, trace_1, trace_2)
fig <- plot_ly(data, x = ~x, y = ~trace_0, name = 'trace 0', type = 'scatter', mode = 'lines')
fig <- fig %>% add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines+markers')
fig <- fig %>% add_trace(y = ~trace_2, name = 'trace 2', mode = 'markers')
fig2.2.3 Density Plot
library(plotly)
dens <- with(diamonds, tapply(price, INDEX = cut, density))
df <- data.frame(
x = unlist(lapply(dens, "[[", "x")),
y = unlist(lapply(dens, "[[", "y")),
cut = rep(names(dens), each = length(dens[[1]]$x))
)
fig <- plot_ly(df, x = ~x, y = ~y, color = ~cut)
fig <- fig %>% add_lines()
fig2.3 Bar Charts
2.3.1 Basic Bar Chart
library(plotly)
fig <- plot_ly(
x = c("giraffes", "orangutans", "monkeys"),
y = c(20, 14, 23),
name = "SF Zoo",
type = "bar"
)
fig2.3.2 Grouped Bar Chart
library(plotly)
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)
fig <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo')
fig <- fig %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group')
fig2.3.3 Stacked Bar Chart
library(plotly)
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)
fig <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo')
fig <- fig %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'stack')
fig2.3.4 Colored and Styled Bar Chart
library(plotly)
x <- c(1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012)
roW <- c(219, 146, 112, 127, 124, 180, 236, 207, 236, 263, 350, 430, 474, 526, 488, 537, 500, 439)
China <- c(16, 13, 10, 11, 28, 37, 43, 55, 56, 88, 105, 156, 270, 299, 340, 403, 549, 499)
data <- data.frame(x, roW, China)
fig <- plot_ly(data, x = ~x, y = ~roW, type = 'bar', name = 'Rest of the World',
marker = list(color = 'rgb(55, 83, 109)'))
fig <- fig %>% add_trace(y = ~China, name = 'China', marker = list(color = 'rgb(26, 118, 255)'))
fig <- fig %>% layout(title = 'US Export of Plastic Scrap',
xaxis = list(
title = "",
tickfont = list(
size = 14,
color = 'rgb(107, 107, 107)')),
yaxis = list(
title = 'USD (millions)',
titlefont = list(
size = 16,
color = 'rgb(107, 107, 107)'),
tickfont = list(
size = 14,
color = 'rgb(107, 107, 107)')),
legend = list(x = 0, y = 1, bgcolor = 'rgba(255, 255, 255, 0)', bordercolor = 'rgba(255, 255, 255, 0)'),
barmode = 'group', bargap = 0.15, bargroupgap = 0.1)
fig2.4 Pie Charts
2.4.1 Basic Pie Chart
library(plotly)
USPersonalExpenditure <- data.frame("Categorie"=rownames(USPersonalExpenditure), USPersonalExpenditure)
data <- USPersonalExpenditure[,c('Categorie', 'X1960')]
fig <- plot_ly(data, labels = ~Categorie, values = ~X1960, type = 'pie')
fig <- fig %>% layout(title = 'United States Personal Expenditures by Categories in 1960',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
fig2.4.2 Donut Chart
library(plotly)
library(dplyr)
# Get Manufacturer
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
df <- mtcars
df <- df %>% group_by(manuf)
df <- df %>% summarize(count = n())
fig <- df %>% plot_ly(labels = ~manuf, values = ~count)
fig <- fig %>% add_pie(hole = 0.6)
fig <- fig %>% layout(title = "Donut charts using Plotly", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
fig2.5 Bubble Charts
2.5.1 Simple Bubble Chart
library(plotly)
data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
fig <- plot_ly(data, x = ~Women, y = ~Men, text = ~School, type = 'scatter', mode = 'markers',
marker = list(size = ~Gap, opacity = 0.5))
fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE))
fig2.5.2 Mapping a Color Variable (Continuous)
library(plotly)
data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
fig <- plot_ly(data, x = ~Women, y = ~Men, text = ~School, type = 'scatter', mode = 'markers', color = ~Gap, colors = 'Reds',
marker = list(size = ~Gap, opacity = 0.5))
fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE))
fig2.5.3 Mapping a Color Variable (Categorical)
library(plotly)
data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
data$State <- as.factor(c('Massachusetts', 'California', 'Massachusetts', 'Pennsylvania', 'New Jersey', 'Illinois', 'Washington DC',
'Massachusetts', 'Connecticut', 'New York', 'North Carolina', 'New Hampshire', 'New York', 'Indiana',
'New York', 'Michigan', 'Rhode Island', 'California', 'Georgia', 'California', 'California'))
fig <- plot_ly(data, x = ~Women, y = ~Men, text = ~School, type = 'scatter', mode = 'markers', size = ~Gap, color = ~State, colors = 'Paired',
marker = list(opacity = 0.5, sizemode = 'diameter'))
fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE),
showlegend = FALSE)
fig2.5.4 Styled Buble Chart
library(plotly)
data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv")
data_2007 <- data[which(data$year == 2007),]
data_2007 <- data_2007[order(data_2007$continent, data_2007$country),]
slope <- 2.666051223553066e-05
data_2007$size <- sqrt(data_2007$pop * slope)
colors <- c('#4AC6B7', '#1972A4', '#965F8A', '#FF7070', '#C61951')
fig <- plot_ly(data_2007, x = ~gdpPercap, y = ~lifeExp, color = ~continent, size = ~size, colors = colors,
type = 'scatter', mode = 'markers', sizes = c(min(data_2007$size), max(data_2007$size)),
marker = list(symbol = 'circle', sizemode = 'diameter',
line = list(width = 2, color = '#FFFFFF')),
text = ~paste('Country:', country, '<br>Life Expectancy:', lifeExp, '<br>GDP:', gdpPercap,
'<br>Pop.:', pop))
fig <- fig %>% layout(title = 'Life Expectancy v. Per Capita GDP, 2007',
xaxis = list(title = 'GDP per capita (2000 dollars)',
gridcolor = 'rgb(255, 255, 255)',
range = c(2.003297660701705, 5.191505530708712),
type = 'log',
zerolinewidth = 1,
ticklen = 5,
gridwidth = 2),
yaxis = list(title = 'Life Expectancy (years)',
gridcolor = 'rgb(255, 255, 255)',
range = c(36.12621671352166, 91.72921793264332),
zerolinewidth = 1,
ticklen = 5,
gridwith = 2),
paper_bgcolor = 'rgb(243, 243, 243)',
plot_bgcolor = 'rgb(243, 243, 243)')
fig2.6 Sankey Diagram
2.6.1 Basic Sankey Diagram
library(plotly)
fig <- plot_ly(
type = "sankey",
orientation = "h",
node = list(
label = c("A1", "A2", "B1", "B2", "C1", "C2"),
color = c("blue", "blue", "blue", "blue", "blue", "blue"),
pad = 15,
thickness = 20,
line = list(
color = "black",
width = 0.5
)
),
link = list(
source = c(0,1,0,2,3,3),
target = c(2,3,3,4,4,5),
value = c(8,4,2,8,4,2)
)
)
fig <- fig %>% layout(
title = "Basic Sankey Diagram",
font = list(
size = 10
)
)
fig2.6.2 Style Sankey Diagram
library(plotly)
library(rjson)
json_file <- "https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy_dark.json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))
fig <- plot_ly(
type = "sankey",
domain = list(
x = c(0,1),
y = c(0,1)
),
orientation = "h",
valueformat = ".0f",
valuesuffix = "TWh",
node = list(
label = json_data$data[[1]]$node$label,
color = json_data$data[[1]]$node$color,
pad = 15,
thickness = 15,
line = list(
color = "black",
width = 0.5
)
),
link = list(
source = json_data$data[[1]]$link$source,
target = json_data$data[[1]]$link$target,
value = json_data$data[[1]]$link$value,
label = json_data$data[[1]]$link$label
)
)
fig <- fig %>% layout(
title = "Energy forecast for 2050<br>Source: Department of Energy & Climate Change, Tom Counsell via <a href='https://bost.ocks.org/mike/sankey/'>Mike Bostock</a>",
font = list(
size = 10,
color = 'white'
),
xaxis = list(showgrid = F, zeroline = F, showticklabels = F),
yaxis = list(showgrid = F, zeroline = F, showticklabels = F),
plot_bgcolor = 'black',
paper_bgcolor = 'black'
)
fig3 Statistical Charts
3.1 2D Histograms
A 2D histogram is a visualization of a bivariate distribution. And it looks like a heat map.
#
library(plotly)
s <- matrix(c(1, -.75, -.75, 1), ncol = 2)
obs <- mvtnorm::rmvnorm(500, sigma = s)
fig <- plot_ly(data = mtcars, x = ~hp, y= ~mpg)
fig2 <- subplot(
fig %>% add_markers(alpha = 0.2),
fig %>% add_histogram2d()
)
fig23.2 Box Plot
4 Scientific Charts
4.2 Contour Plots
4.2.2 Smoothing Contour Coloring
library(plotly)
fig <- plot_ly(
type = 'contour',
z = matrix(c(10, 10.625, 12.5, 15.625, 20, 5.625, 6.25, 8.125,
11.25, 15.625, 2.5, 3.125, 5, 8.125, 12.5, 0.625,
1.25, 3.125, 6.25, 10.625, 0, 0.625, 2.5, 5.625,
10), nrow=5, ncol=5),
contours = list(
coloring = 'heatmap'
)
)
fig4.4 Parallel Coordinates
4.4.1 Basic Parallel Cordinates Plots
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/iris.csv")
fig <- df %>% plot_ly(type = 'parcoords',
line = list(color = ~species_id,
colorscale = list(c(0,'red'),c(0.5,'green'),c(1,'blue'))),
dimensions = list(
list(range = c(2,4.5),
label = 'Sepal Width', values = ~sepal_width),
list(range = c(4,8),
constraintrange = c(5,6),
label = 'Sepal Length', values = ~sepal_length),
list(range = c(0,2.5),
label = 'Petal Width', values = ~petal_width),
list(range = c(1,7),
label = 'Petal Length', values = ~petal_length)
)
)
fig4.4.2 Advanced Parallel Coordinates Plot
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/parcoords_data.csv")
fig <- df %>%
plot_ly(width = 1000, height = 600)
fig <- fig %>% add_trace(type = 'parcoords',
line = list(color = ~colorVal,
colorscale = 'Jet',
showscale = TRUE,
reversescale = TRUE,
cmin = -4000,
cmax = -100),
dimensions = list(
list(range = c(~min(blockHeight),~max(blockHeight)),
constraintrange = c(100000,150000),
label = 'Block Height', values = ~blockHeight),
list(range = c(~min(blockWidth),~max(blockWidth)),
label = 'Block Width', values = ~blockWidth),
list(tickvals = c(0,0.5,1,2,3),
ticktext = c('A','AB','B','Y','Z'),
label = 'Cyclinder Material', values = ~cycMaterial),
list(range = c(-1,4),
tickvals = c(0,1,2,3),
label = 'Block Material', values = ~blockMaterial),
list(range = c(~min(totalWeight),~max(totalWeight)),
visible = TRUE,
label = 'Total Weight', values = ~totalWeight),
list(range = c(~min(assemblyPW),~max(assemblyPW)),
label = 'Assembly Penalty Weight', values = ~assemblyPW),
list(range = c(~min(HstW),~max(HstW)),
label = 'Height st Width', values = ~HstW),
list(range = c(~min(minHW),~max(minHW)),
label = 'Min Height Width', values = ~minHW),
list(range = c(~min(minWD),~max(minWD)),
label = 'Min Width Diameter', values = ~minWD),
list(range = c(~min(rfBlock),~max(rfBlock)),
label = 'RF Block', values = ~rfBlock)
)
)
fig4.5 Polar Charts
4.5.1 Basic Polar Charts
library(plotly)
fig <- plot_ly(
type = 'scatterpolar',
r = c(0,1,2,2),
theta = c(0,45,90,0),
mode = 'markers'
)
fig4.5.2 Line Polar Charts
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/polar_dataset.csv")
fig <- plot_ly(
df,
type = 'scatterpolar',
mode = 'lines'
)
fig <- fig %>%
add_trace(
r = ~x1,
theta = ~y,
name = 'Figure8',
line = list(
color = 'peru'
)
)
fig <- fig %>%
add_trace(
r = ~x2,
theta = ~y,
name = 'Cardioid',
line = list(
color = 'darkviolet'
)
)
fig <- fig %>%
add_trace(
r = ~x3,
theta = ~y,
name = 'Hypercardioid',
line = list(
color = 'deepskyblue'
)
)
fig <- fig %>%
add_trace(
r = ~x4,
theta = ~y,
name = 'Subcardioid',
line = list(
color = 'orangered'
)
)
fig <- fig %>%
add_trace(
r = ~x5,
theta = ~y,
name = 'Supercardioid',
line = list(
color = 'green'
)
)
fig <- fig %>%
layout(
title = 'Mic Patterns',
font = list(
family = 'Arial',
size = 12,
color = '#000'
),
showlegend = F
)
fig4.5.3 Area Polar Area
library(plotly)
fig <- plot_ly(
type = 'scatterpolar',
mode = 'lines'
)
fig <- fig %>%
add_trace(
r = c(0, 1.5, 1.5, 0, 2.5, 2.5, 0),
theta = c(0, 10, 25, 0, 205, 215, 0),
fill = 'toself',
fillcolor = '#709Bff',
line = list(
color = 'black'
)
)
fig <- fig %>%
add_trace(
r = c(0, 3.5, 3.5, 0),
theta = c(0, 55, 75, 0),
fill = 'toself',
fillcolor = '#E4FF87',
line = list(
color = 'black'
)
)
fig <- fig %>%
add_trace(
r = c(0, 4.5, 4.5, 0, 4.5, 4.5, 0),
theta = c(0, 100, 120, 0, 305, 320, 0),
fill = 'toself',
fillcolor = '#FFAA70',
line = list(
color = 'black'
)
)
fig <- fig %>%
add_trace(
r = c(0, 4, 4, 0),
theta = c(0, 165, 195, 0),
fill = 'toself',
fillcolor = '#FFDF70',
line = list(
color = 'black'
)
)
fig <- fig %>%
add_trace(
r = c(0, 3, 3, 0),
theta = c(0, 262.5, 277.5, 0),
fill = 'toself',
fillcolor = '#B6FFB4',
line = list(
color = 'black'
)
)
fig <- fig %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0,5)
)
),
showlegend = F
)
fig4.6 Radar Charts
4.6.1 Basic Radar Charts
library(plotly)
fig <- plot_ly(
type = 'scatterpolar',
r = c(39, 28, 8, 7, 28, 39),
theta = c('A','B','C', 'D', 'E', 'A'),
fill = 'toself'
)
fig <- fig %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0,50)
)
),
showlegend = F
)
fig4.6.2 Multiple Trace Radar Charts
library(plotly)
fig <- plot_ly(
type = 'scatterpolar',
fill = 'toself'
)
fig <- fig %>%
add_trace(
r = c(39, 28, 8, 7, 28, 39),
theta = c('A','B','C', 'D', 'E', 'A'),
name = 'Group A'
)
fig <- fig %>%
add_trace(
r = c(1.5, 10, 39, 31, 15, 1.5),
theta = c('A','B','C', 'D', 'E', 'A'),
name = 'Group B'
)
fig <- fig %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0,50)
)
)
)
fig5 Financial Charts
5.1 Time Series and Date Axess
5.1.1 Time Series using Axes of type date
library(plotly)
stock <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
fig <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
add_trace(x = ~Date, y = ~AAPL.High)%>%
layout(showlegend = F)
fig <- fig %>%
layout(
xaxis = list(zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6', width = 900)
fig5.1.2 Configuring Tick Labels
library(tidyquant)
library(plotly)
tickers = c("GOOG", "AAPL", "AMZN", "META", "NFLX", "MSFT")
for (i in tickers){
getSymbols(i,
from = "2020-01-01",
to = "2021-12-31")}
stock <- data.frame(GOOG$GOOG.Adjusted,
AAPL$AAPL.Adjusted,
AMZN$AMZN.Adjusted,
META$META.Adjusted,
NFLX$NFLX.Adjusted,
MSFT$MSFT.Adjusted)
stock$GOOG.Adjusted <- stock$GOOG.Adjusted/stock$GOOG.Adjusted[1]
stock$AAPL.Adjusted <- stock$AAPL.Adjusted/stock$AAPL.Adjusted[1]
stock$AMZN.Adjusted <- stock$AMZN.Adjusted/stock$AMZN.Adjusted[1]
stock$META.Adjusted <- stock$META.Adjusted/stock$META.Adjusted[1]
stock$NFLX.Adjusted <- stock$NFLX.Adjusted/stock$NFLX.Adjusted[1]
stock$MSFT.Adjusted <- stock$MSFT.Adjusted/stock$MSFT.Adjusted[1]
stock <- data.frame(stock,rownames(stock))
colnames(stock) <- append(tickers,'Dates')
fig <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
add_trace(x = ~Dates, y = ~GOOG, name = 'GOOG')%>%
add_trace(x = ~Dates, y = ~AAPL, name = 'AAPL')%>%
add_trace(x = ~Dates, y = ~AMZN, name = 'AMZN')%>%
add_trace(x = ~Dates, y = ~META, name = 'META')%>%
add_trace(x = ~Dates, y = ~NFLX, name = 'NFLX')%>%
add_trace(x = ~Dates, y = ~MSFT, name = 'MSFT')%>%
layout(title = 'custom tick labels',legend=list(title=list(text='variable')),
xaxis = list(dtick = "M1", tickformat="%b<br>%Y"), width = 1000)
options(warn = -1)
fig <- fig %>%
layout(
xaxis = list(zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
fig5.2 Candlestick Charts
5.2.1 Basic Candlestick
library(plotly)
library(quantmod)
getSymbols("AAPL",src='yahoo')
# basic example of ohlc charts
df <- data.frame(Date=index(AAPL),coredata(AAPL))
df <- tail(df, 30)
fig <- df %>% plot_ly(x = ~Date, type="candlestick",
open = ~AAPL.Open, close = ~AAPL.Close,
high = ~AAPL.High, low = ~AAPL.Low)
fig <- fig %>% layout(title = "Basic Candlestick Chart")
fig## [1] "AAPL"
5.2.2 Customise the fig ure with Shapes and Annotations
library(plotly)
library(quantmod)
getSymbols("AAPL",src='yahoo')
df <- data.frame(Date=index(AAPL),coredata(AAPL))
# annotation
a <- list(text = "Stock Split",
x = '2014-06-06',
y = 1.02,
xref = 'x',
yref = 'paper',
xanchor = 'left',
showarrow = FALSE
)
# use shapes to create a line
l <- list(type = line,
x0 = '2014-06-06',
x1 = '2014-06-06',
y0 = 0,
y1 = 1,
xref = 'x',
yref = 'paper',
line = list(color = 'black',
width = 0.5)
)
fig <- df %>% plot_ly(x = ~Date, type="candlestick",
open = ~AAPL.Open, close = ~AAPL.Close,
high = ~AAPL.High, low = ~AAPL.Low)
fig <- fig %>% layout(title = "Apple Stock",
annotations = a,
shapes = l)
fig## [1] "AAPL"
5.3 OHLC Charts
5.3.1 Basic OHLC Chart
library(plotly)
library(quantmod)
getSymbols("AAPL",src='yahoo')
df <- data.frame(Date=index(AAPL),coredata(AAPL))
df <- tail(df, 30)
fig <- df %>% plot_ly(x = ~Date, type="ohlc",
open = ~AAPL.Open, close = ~AAPL.Close,
high = ~AAPL.High, low = ~AAPL.Low)
fig <- fig %>% layout(title = "Basic OHLC Chart",
xaxis = list(rangeslider = list(visible = F)))
fig## [1] "AAPL"
5.3.2 Customise the Figure with Shapes and Annotations
library(plotly)
library(quantmod)
getSymbols("AAPL",src='yahoo')
df <- data.frame(Date=index(AAPL),coredata(AAPL))
# annotation
a <- list(text = "Stock Split",
x = '2014-06-06',
y = 1.02,
xref = 'x',
yref = 'paper',
xanchor = 'left',
showarrow = FALSE
)
# use shapes to create a line
l <- list(type = line,
x0 = '2014-06-06',
x1 = '2014-06-06',
y0 = 0,
y1 = 1,
xref = 'x',
yref = 'paper',
line = list(color = 'black',
width = 0.5)
)
fig <- df %>% plot_ly(x = ~Date, type="ohlc",
open = ~AAPL.Open, close = ~AAPL.Close,
high = ~AAPL.High, low = ~AAPL.Low)
fig <- fig %>% layout(title = "Custom Colors",
annotations = a,
shapes = l)
fig## [1] "AAPL"
5.4 Waterfall Charts
5.4.1 Basic Waterfall Chart
library(plotly)
x= list("Sales", "Consulting", "Net revenue", "Purchases", "Other expenses", "Profit before tax")
measure= c("relative", "relative", "total", "relative", "relative", "total")
text= c("+60", "+80", "", "-40", "-20", "Total")
y= c(60, 80, 0, -40, -20, 0)
data = data.frame(x=factor(x,levels=x),measure,text,y)
fig <- plot_ly(
data, name = "20", type = "waterfall", measure = ~measure,
x = ~x, textposition = "outside", y= ~y, text =~text,
connector = list(line = list(color= "rgb(63, 63, 63)")))
fig <- fig %>%
layout(title = "Profit and loss statement 2018",
xaxis = list(title = ""),
yaxis = list(title = ""),
autosize = TRUE,
showlegend = TRUE)
fig5.5 Funnel Charts
# Need to install plotly from Github to get funnel plots
devtools::install_github("ropensci/plotly")5.5.1 Basic Funnel Plot
library(plotly)
fig <- plot_ly()
fig <- fig %>%
add_trace(
type = "funnel",
y = c("Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent"),
x = c(39, 27.4, 20.6, 11, 2))
fig <- fig %>%
layout(yaxis = list(categoryarray = c("Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent")))
fig5.5.2 Stacked Funnel Plot
library(plotly)
fig <- plot_ly(
type = "funnel",
name = 'Montreal',
y = c("Website visit", "Downloads", "Potential customers", "Requested price"),
x = c(120, 60, 30, 20),
textinfo = "value+percent initial")
fig <- fig %>%
add_trace(
type = "funnel",
name = 'Toronto',
orientation = "h",
y = c("Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent"),
x = c(100, 60, 40, 30, 20),
textposition = "inside",
textinfo = "value+percent previous")
fig <- fig %>%
add_trace(
type = "funnel",
name = 'Vancouver',
orientation = "h",
y = c("Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent", "Finalized"),
x = c(90, 70, 50, 30, 10, 5),
textposition = "outside",
textinfo = "value+percent total")
fig <- fig %>%
layout(yaxis = list(categoryarray = c("Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent", "Finalized")))
fig6 Maps
6.1 Choropleth Maps
6.1.1 Choropleth Map Using GeoJSON
library(plotly)
library(rjson)
url <- 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
counties <- rjson::fromJSON(file=url)
url2<- "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
df <- read.csv(url2, colClasses=c(fips="character"))
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
fig <- plot_ly()
fig <- fig %>% add_trace(
type="choropleth",
geojson=counties,
locations=df$fips,
z=df$unemp,
colorscale="Viridis",
zmin=0,
zmax=12,
marker=list(line=list(
width=0)
)
)
fig <- fig %>% colorbar(title = "Unemployment Rate (%)")
fig <- fig %>% layout(
title = "2016 US Unemployment by County"
)
fig <- fig %>% layout(
geo = g
)
fig6.1.2 Indexing by GeoJSON Properties
library(plotly)
library(rjson)
url <- 'https://raw.githubusercontent.com/plotly/datasets/master/election.geojson'
geojson <- rjson::fromJSON(file=url)
url2<- "https://raw.githubusercontent.com/plotly/datasets/master/election.csv"
df <- read.csv(url2)
g <- list(
fitbounds = "locations",
visible = FALSE
)
fig <- plot_ly()
fig <- fig %>% add_trace(
type="choropleth",
geojson=geojson,
locations=df$district,
z=df$Bergeron,
colorscale="Viridis",
featureidkey="properties.district"
)
fig <- fig %>% layout(
geo = g
)
fig <- fig %>% colorbar(title = "Bergeron Votes")
fig <- fig %>% layout(
title = "2013 Montreal Election"
)
fig6.1.3 Customize choropleth chart
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv")
df$hover <- with(df, paste(state, '<br>', "Beef", beef, "Dairy", dairy, "<br>",
"Fruits", total.fruits, "Veggies", total.veggies,
"<br>", "Wheat", wheat, "Corn", corn))
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
fig <- plot_geo(df, locationmode = 'USA-states')
fig <- fig %>% add_trace(
z = ~total.exports, text = ~hover, locations = ~code,
color = ~total.exports, colors = 'Purples'
)
fig <- fig %>% colorbar(title = "Millions USD")
fig <- fig %>% layout(
title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = g
)
fig6.1.4 World Choropleth Map
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
# light grey boundaries
l <- list(color = toRGB("grey"), width = 0.5)
# specify map projection/options
g <- list(
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = 'Mercator')
)
fig <- plot_geo(df)
fig <- fig %>% add_trace(
z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Blues',
text = ~COUNTRY, locations = ~CODE, marker = list(line = l)
)
fig <- fig %>% colorbar(title = 'GDP Billions US$', tickprefix = '$')
fig <- fig %>% layout(
title = '2014 Global GDP<br>Source:<a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">CIA World Factbook</a>',
geo = g
)
fig6.2 Scatter Plots on Maps
6.2.1 Basic Scatter on Map
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
# geo styling
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray95"),
subunitcolor = toRGB("gray85"),
countrycolor = toRGB("gray85"),
countrywidth = 0.5,
subunitwidth = 0.5
)
fig <- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
)
fig <- fig %>% colorbar(title = "Incoming flights<br />February 2011")
fig <- fig %>% layout(
title = 'Most trafficked US airports<br />(Hover for airport)', geo = g
)
fig6.2.2 Style Scatter Map Layout
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2015_06_30_precipitation.csv')
# change default color scale title
m <- list(colorbar = list(title = "Total Inches"))
# geo styling
g <- list(
scope = 'north america',
showland = TRUE,
landcolor = toRGB("grey83"),
subunitcolor = toRGB("white"),
countrycolor = toRGB("white"),
showlakes = TRUE,
lakecolor = toRGB("white"),
showsubunits = TRUE,
showcountries = TRUE,
resolution = 50,
projection = list(
type = 'conic conformal',
rotation = list(lon = -100)
),
lonaxis = list(
showgrid = TRUE,
gridwidth = 0.5,
range = c(-140, -55),
dtick = 5
),
lataxis = list(
showgrid = TRUE,
gridwidth = 0.5,
range = c(20, 60),
dtick = 5
)
)
fig <- plot_geo(df, lat = ~Lat, lon = ~Lon, color = ~Globvalue)
fig <- fig %>% add_markers(
text = ~paste(df$Globvalue, "inches"), hoverinfo = "text"
)
fig <- fig %>% layout(title = 'US Precipitation 06-30-2015<br>Source: NOAA', geo = g)
fig6.3 Mapbox Density
6.3.1 Mapbox Access Token
library(plotly)
quakes = read.csv('https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv')
fig <- quakes
fig <- fig %>%
plot_ly(
type = 'densitymapbox',
lat = ~Latitude,
lon = ~Longitude,
coloraxis = 'coloraxis',
radius = 10)
fig <- fig %>%
layout(
mapbox = list(
style="stamen-terrain",
center= list(lon=180)), coloraxis = list(colorscale = "Viridis"))
fig6.4 Mapbox Layers
6.4.1 OpenStreetMap Tiles, no Token Needed
library(plotly)
us_cities = read.csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
fig <- us_cities
fig <- fig %>%
plot_ly(
lat = ~lat,
lon = ~lon,
marker = list(color = "fuchsia"),
type = 'scattermapbox',
hovertext = us_cities[,"City"])
fig <- fig %>%
layout(
mapbox = list(
style = 'open-street-map',
zoom =2.5,
center = list(lon = -88, lat = 34)))
fig6.4.2 Base Map Below A Trace: No Token Needed
library(plotly)
us_cities = read.csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
fig <- us_cities
fig <- fig %>%
plot_ly(
lat = ~lat,
lon = ~lon,
type = "scattermapbox",
hovertext = us_cities[,"City"],
marker = list(color = "fuchsia"))
fig <- fig %>%
layout(mapbox= list(
style = "white-bg",
zoom = 3,
center = list(lon = -93 ,lat= 41),
layers = list(list(
below = 'traces',
sourcetype = "raster",
source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}")))))
fig6.5 Bubble Maps
6.5.1 United States Bubble Map
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')
df$q <- with(df, cut(pop, quantile(pop)))
levels(df$q) <- paste(c("1st", "2nd", "3rd", "4th", "5th"), "Quantile")
df$q <- as.ordered(df$q)
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray85"),
subunitwidth = 1,
countrywidth = 1,
subunitcolor = toRGB("white"),
countrycolor = toRGB("white")
)
fig <- plot_geo(df, locationmode = 'USA-states', sizes = c(1, 250))
fig <- fig %>% add_markers(
x = ~lon, y = ~lat, size = ~pop, color = ~q, hoverinfo = "text",
text = ~paste(df$name, "<br />", df$pop/1e6, " million")
)
fig <- fig %>% layout(title = '2014 US city populations<br>(Click legend to toggle)', geo = g)
fig8 3D Charts
8.0.1 Basic 3D Scatter Plot
library(plotly)
mtcars$am[which(mtcars$am == 0)] <- 'Automatic'
mtcars$am[which(mtcars$am == 1)] <- 'Manual'
mtcars$am <- as.factor(mtcars$am)
fig <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec, color = ~am, colors = c('pink', 'blue'))
fig <- fig %>% add_markers(size = 10)
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Weight'),
yaxis = list(title = 'Gross horsepower'),
zaxis = list(title = '1/4 mile time')))
fig9 Transforms
9.2 Group
9.2.1 Basic Example
library(plotly)
fig <- plot_ly(
type = 'scatter',
x = mtcars$hp,
y = mtcars$qsec,
text = paste("Make: ", rownames(mtcars),
"<br>hp: ", mtcars$hp,
"<br>qsec: ", mtcars$qsec,
"<br>Cyl: ", mtcars$cyl),
hoverinfo = 'text',
mode = 'markers',
transforms = list(
list(
type = 'groupby',
groups = mtcars$cyl,
styles = list(
list(target = 4, value = list(marker =list(color = 'blue'))),
list(target = 6, value = list(marker =list(color = 'red'))),
list(target = 8, value = list(marker =list(color = 'black')))
)
)
)
)
fig9.3 Aggregation
9.3.1 Basic Example
library(plotly)
fig <- plot_ly(
type = 'scatter',
x = diamonds$cut,
y = diamonds$price,
mode = 'markers',
transforms = list(
list(
type = 'aggregate',
groups = diamonds$cut,
aggregations = list(
list(
target = 'y', func = 'sum', enabled = T
)
)
)
)
)
fig9.3.2 Histogram Binning
library(plotly)
df <- read.csv("https://plotly.com/~public.health/17.csv", skipNul = TRUE, encoding = "UTF-8")
labels <- function(size, label) {
list(
args = c("xbins.size", size),
label = label,
method = "restyle"
)
}
fig <- df %>%
plot_ly(
x = ~date,
autobinx = FALSE,
autobiny = TRUE,
marker = list(color = "rgb(68, 68, 68)"),
name = "date",
type = "histogram",
xbins = list(
end = "2016-12-31 12:00",
size = "M1",
start = "1983-12-31 12:00"
)
)
fig <- fig %>% layout(
paper_bgcolor = "rgb(240, 240, 240)",
plot_bgcolor = "rgb(240, 240, 240)",
title = "<b>Shooting Incidents</b><br>use dropdown to change bin size",
xaxis = list(
type = 'date'
),
yaxis = list(
title = "Incidents"
),
updatemenus = list(
list(
x = 0.1,
y = 1.15,
active = 1,
showactive = TRUE,
buttons = list(
labels("D1", "Day"),
labels("M1", "Month"),
labels("M6", "Half Year"),
labels("M12", "Year")
)
)
)
)
fig9.3.3 Mapping with Aggregations
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/worldhappiness.csv")
s <- schema()
agg <- s$transforms$aggregate$attributes$aggregations$items$aggregation$func$values
l = list()
for (i in 1:length(agg)) {
ll = list(method = "restyle",
args = list('transforms[0].aggregations[0].func', agg[i]),
label = agg[i])
l[[i]] = ll
}
fig <- df %>%
plot_ly(
type = 'choropleth',
locationmode = 'country names',
locations = ~Country,
z = ~HappinessScore,
autocolorscale = F,
reversescale = T,
colorscale = 'Portland',
transforms = list(list(
type = 'aggregate',
groups = ~Country,
aggregations = list(
list(target = 'z', func = 'sum', enabled = T)
)
))
)
fig <- fig %>% layout(
title = "<b>World Happiness</b>",
geo = list(
showframe = F,
showcoastlines = F
),
updatemenus = list(
list(
x = 0.25,
y = 1.04,
xref = 'paper',
yref = 'paper',
yanchor = 'top',
buttons = l
)
)
)
fig